var express = require('express');
var router = express.Router();
const User = require('../models/User');
const Product = require('../models/Product');
const OutboundOrder = require('../models/OutboundOrder');
const { generateToken } = require('../utils/jwt');
/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

// 注册接口（账号、密码、邮箱）- 明文存储
router.post('/register', async (req, res) => {
  try {
    const { account, password, email, name } = req.body;
    // 校验账号唯一性
    const existingUser = await User.findOne({ account });
    if (existingUser) {
      return res.status(400).json({ message: '该账号已注册' });
    }
    // 直接保存明文密码（注意：生产环境不建议）
    const newUser = new User({ name, account, password, email });
    await newUser.save();
    // 隐藏密码返回
    const { _id, name: userName, account: userAccount, email: userEmail, registerTime } = newUser;
    res.status(201).json({ 
      message: '注册成功', 
      user: { _id, userName, userAccount, userEmail, registerTime } 
    });
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
});

// 登录接口（账号、密码）- 明文验证
router.post('/login', async (req, res) => {
  try {
    const { account, password } = req.body;
    // 查找用户
    const user = await User.findOne({ account });
    if (!user) {
      return res.status(404).json({ message: '用户不存在' });
    }
    // 直接比较明文密码
    if (user.password !== password) {
      return res.status(400).json({ message: '密码错误' });
    }

    // 生成JWT令牌
    const token = generateToken({ id: user._id, account: user.account });
    
    // 返回登录成功信息和令牌
    const { _id, name, account: userAccount, email } = user;
    res.json({ 
      message: '登录成功',
      token,  // 确保返回令牌
      user: { _id, name, userAccount, email } 
    });
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
});

// 添加订单接口（用户id、商品id、数量）
router.post('/orders', async (req, res) => {
  try {
    const { userId, productId, quantity, userName, phone, address } = req.body;
    // 校验用户存在
    const user = await User.findById(userId);
    if (!user) return res.status(404).json({ message: '用户不存在' });
    
    // 校验商品存在
    const product = await Product.findById(productId);
    if (!product) return res.status(404).json({ message: '商品不存在' });
    
    // 创建出库订单（关联用户和商品）
    const newOrder = new OutboundOrder({
      productId,
      productName: product.name,
      quantity,
      userName,
      phone,
      address,
      status: '待审核'
    });
    await newOrder.save();
    
    res.status(201).json({ 
      message: '订单创建成功', 
      order: newOrder 
    });
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
});

module.exports = router;
